<template>
	<view class="pt-md" :style="{background:pageColor}" v-if="isLoad">
		<view class="ml-md mr-md radius-32 fill-base pd-lg partner-info">
			<view class="flex-between pb-lg">
				<image :src="detail.cover" mode="aspectFill" class="cover radius-16"></image>
				<view class="flex-1 pl-md">
					<view class="f-mini-title text-bold ellipsis max-450">{{detail.title}}</view>
					<view class="flex-y-baseline" style="color: #FF3C6E;padding-top: 24rpx;" v-if="detail.money_type == 3">
						<text>¥</text>
						<text class="f-md-title text-bold">{{detail.join_price}}</text>
						<text class="f-desc">/人</text>
					</view>
					<view style="color: #FF3C6E;padding-top: 24rpx;" v-else>免费</view>
				</view>
			</view>
			<view class="detail-time radius-16 pl-md pr-md flex-y-center f-desc">
				<text class="f-desc">还有</text>
				<min-countdown :type="3" :color="primaryColor" :bgColor="bgColor" countdownClass="partner-detail"
					:targetTime="detail.join_end_time*1000" @callback="countEnd"></min-countdown>
				<text class="f-desc" style="padding-left: 12rpx;">报名结束</text>
			</view>
			<view class="pt-lg flex-y-center b-1px-b" style="padding-bottom: 25rpx;">
				<view class="left-icon flex-y-center">
					<i class="iconfont iconshijianguanli text-bold"></i>
				</view>
				<view class="flex-y-center f-desc text-bold">
					{{$util.formatTime(detail.start_time*1000,'YY.M.D h:m')}} - {{$util.formatTime(detail.end_time*1000,'YY.M.D h:m')}}
				</view>
			</view>
			<view class="pt-lg flex-y-center rel">
				<view class="left-icon flex-y-center">
					<i class="iconfont icondizhiguanli3 text-bold" style="font-size: 18px;"></i>
				</view>
				<view class="flex f-desc text-bold">
					<!-- <text class="pr-sm">12km</text> -->
					<view class="max-400 ellipsis">{{detail.address}}</view>
				</view>
				<image @tap.stop="toMap" class="addr-icon abs" src="https://www.peikangbao.cn/admin/anmo/partner/partner-addr.png" mode="aspectFill"></image>
			</view>
			<view class="pt-sm f-desc" style="color: #A3A3A3;padding-left: 151rpx;" v-if="detail.address_info">({{detail.address_info}})</view>
		</view>
		<view class="mt-md ml-md mr-md pl-lg pr-lg fill-base radius-16">
			<view class="f-title text-bold" style="padding-top: 26rpx;">报名信息</view>
			<view class="form-item b-1px-b flex-between">
				<view class="form-item-title text-bold f-desc">昵称</view>
				<view class="f-desc text-bold flex-1">{{mineInfo.nickName || ''}}</view>
			</view>
			<view class="form-item b-1px-b flex-between">
				<view class="form-item-title text-bold f-desc">手机号</view>
				<block v-if="mineInfo.phone && isEditPhone">
					<view class="flex-between flex-1">
						<view class="f-desc text-bold flex-1">{{mineInfo.phone}}</view>
						<view class="form-item-btn f-desc flex-center c-base"
						:style="{background: primaryColor}" @tap="toReplace">更换</view>
					</view>
				</block>
				<block v-else>
					<input class="form-item-input flex-1" type="text" placeholder="请输入手机号" v-model="form.phone"/>
					<view class="form-item-btn f-desc flex-center" v-if="configInfo.short_code_status"
					:style="{color: primaryColor,borderColor: primaryColor}" @tap="toSend">{{ authTime ? `(${authTime}s)` : '验证码'}}</view>
				</block>
			</view>
			<view class="form-item b-1px-b flex-between" v-if="(!mineInfo.phone || !isEditPhone) && configInfo.short_code_status">
				<view class="form-item-title text-bold f-desc">验证码</view>
				<input class="form-item-input flex-1" type="text" placeholder="请输入验证码" v-model="form.code"/>
			</view>
			
			<block v-for="(item,index) in form.field" :key="index">
				<view class="form-item b-1px-b" v-if="item.type == 3">
					<view class="form-item-title text-bold f-desc h-90 flex-y-center">{{item.name}}</view>
					<view class="pb-lg">
						<upload @upload="imgUpload($event, index)" :imagelist="item.value" imgtype="value"
							text="上传图片" :imgsize="1">
						</upload>
					</view>
				</view>
				
				<block v-if="item.type == 2">
					<picker @change="pickerChange($event, index)" :value="item.ind" :range="item.select">
						<view class="form-item b-1px-b flex-between">
							<view class="form-item-title text-bold f-desc">{{item.name}}</view>
							<view class="flex-center">
								<text class="pr-sm">{{item.ind > -1 ? item.select[item.ind] : '请选择'}}</text>
								<i class="iconfont icon-right text-bold" style="color: #9B9B9B;font-size: 13px;"></i>
							</view>
						</view>
					</picker>
				</block>
				
				<view class="form-item b-1px-b flex-between" v-if="item.type == 1">
					<view class="form-item-title text-bold f-desc pr-lg">{{item.name}}</view>
					<input class="form-item-input flex-1" type="text" maxlength="400" :placeholder="`请输入${item.name}`" v-model="item.value"/>
				</view>
			</block>
			
		</view>
		<view class="mt-md radius-16 fill-base pl-lg pr-lg pb-lg ml-md mr-md">
			<view class="flex-y-center text-bold f-title h-90">报名备注</view>
			<view class="radius-16 pb-md" style="background-color: #F7F7F7;">
				<textarea v-model="form.text" class="form-item-textarea pl-lg pr-lg pt-lg" maxlength="300" name="" id="" cols="30" rows="10" placeholder="请输入报名备注"></textarea>
				<view class="text-right c-caption pt-sm pr-lg">{{form.text.length > 300 ? 300 : form.text.length}}/300</view>
			</view>
		</view>
		<view class="mt-md radius-16 fill-base pl-lg pr-lg pb-lg ml-md mr-md">
			<view class="flex-y-center text-bold f-title h-90">报名须知</view>
			<view class="c-paragraph">
				1、活动报名后，在活动开始前{{detail.sign_start_minute | handleTime}}个小时将无法取消<br/>
				2、报名成功后可在个人中心-组局记录里进行查看<br/>
				3、活动开始前参与人出示签到码，局主扫码核销<br/>
				4、若未参加活动请及时取消报名，否则会扣取相应费用<br/>
				5、取消报名或者局主驳回报名申请后，报名费用将在24小时内原路退回
			</view>
		</view>
		
		<view class="space-max-footer"></view>
		<fixed position="bottom">
			<view class="fill-base">
				<view class="footer-box flex-between pl-lg pr-lg">
					<view class="flex-center pl-sm f-title text-bold" style="color: #FF4C88;">
						<block v-if="detail.join_price*1 > 0">
							¥{{detail.join_price}}
						</block>
						<block v-else>免费</block>
					</view>
					<view class="footer-box-btn c-base f-ms-title flex-center" :style="{background: primaryColor}" @tap="submit">立即报名</view>
				</view>
				<view class="space-safe"></view>
			</view>
		</fixed>
		
		<uni-popup ref="show_payment" type="bottom" :maskClick="true" :zIndex="996">
			<view class="pl-lg pr-lg payment-box fill-base">
				<view class="flex-center pt-lg pb-lg b-1px-b f-title text-bold">支付方式</view>
				<view class="flex-between pt-lg pb-lg" :class="[{'b-1px-t': index > 0}]" @tap="handlePayment(index)"
				v-for="(item,index) in payList" :key="index" >
					<i class="iconfont mr-md" :class="item.icon" style="font-size: 26px;"></i>
					<view class="flex-y-center flex-1">
						<view class="f-title c-title">{{item.title}}</view>
						<view class="f-paragraph c-caption ml-md" v-if="item.id == 2">
							余额{{mineInfo.some_balance || 0}}元
						</view>
					</view>
					<i class="iconfont" :class="[{'icon-radio-fill': payInd == index}, {'icon-xuanze': payInd != index}]" 
					:style="{color:payInd == index ? primaryColor:'#999'}" style="font-size: 20px;"></i>
				</view>
				<view class="space-max-footer"></view>
			</view>
		</uni-popup>
		
		<!-- #ifdef MP-WEIXIN -->
		<user-privacy ref="user_privacy" :show="false"></user-privacy>
		<!-- #endif -->
	</view>
</template>

<script>
	import {
		mapState,
		mapActions,
		mapMutations
	} from "vuex"
	export default {
		data() {
			return {
				options: {},
				isLoad: false,
				detail: {},
				bgColor: '',
				form: {
					id: '',
					phone: '',
					code: '',
					text: '',
					field: [],
					pay_model: ''
				},
				subRule: [{
					name: "phone",
					checkType: "isMobile",
					errorMsg: "请输入手机号",
					regText: "手机号"
				}, {
					name: "code",
					checkType: "isNotNull",
					errorMsg: "请输入短信验证码"
				}],
				payList: [{
					id: 2,
					icon: 'iconqianbao c-balance',
					title: '账户余额'
				}],
				payInd: 0,
				timer: null,
				authTime: 0,
				isEditPhone: true
			}
		},
		computed: mapState({
			configInfo: state => state.config.configInfo,
			mineInfo: state => state.user.mineInfo,
		}),
		onLoad(options) {
			this.options = options
			this.$util.showLoading()
			this.initIndex()
		},
		filters: {
			handleTime(val){
				let time = {
					30: '半',
					60: 1,
					120: 2
				}
				return time[val]
			}
		},
		methods: {
			...mapActions(['getConfigInfo', 'getUserInfo', 'getMineInfo', 'updateCommonOptions']),
			...mapMutations(['updateUserItem', 'updateOrderItem']),
			async initIndex(refresh = false) {
				await this.getConfigInfo()
				await this.getMineInfo()
				let {
					app_wechat_pay = 0,
					alipay_status = 0,
					recharge_status = 0
				} = this.configInfo
				let weixinInd = this.payList.findIndex(item => {
					return item.id == 1
				})
				if (app_wechat_pay && weixinInd == -1) {
					this.payList.unshift({
						id: 1,
						icon: 'iconweixinzhifu1 c-wechat',
						title: '微信支付'
					})
				}
				
				// #ifndef MP-WEIXIN 
				let alipayInd = this.payList.findIndex(item => {
					return item.id == 3
				})
				if (alipay_status && alipayInd == -1) {
					this.payList.splice(this.payList.length - 1, 0, {
						id: 3,
						icon: 'icon-alipay c-alipay',
						title: '支付宝支付'
					})
				}
				// #endif
				
				if (!recharge_status) {
					let rechargeInd = this.payList.findIndex(item => {
						return item.id == 2
					})
					if (rechargeInd != -1) {
						this.payList.splice(rechargeInd, 1)
					}
				}
				
				this.$util.setNavigationBarColor({
					bg: this.primaryColor
				})
				this.bgColor = this.$util.rgbColor(this.primaryColor, 0.1)
				this.getDetail()
				// #ifdef H5
				if (!refresh) {
					this.$jweixin.hideOptionMenu()
				}
				// #endif
			},
			handlePayment(index){
				let {
					join_price = 0
				} = this.detail
				let {
					some_balance: balance = 0
				} = this.mineInfo
				if(join_price*1 > balance*1 && this.payList[index].id == 2){
					this.$util.showToast({
						title: `账户余额不足`
					})
					return
				}
				this.payInd = index
			},
			async getDetail(){
				let data = await this.$api.partner.getPartnerInfo({id: this.options.id})
				data.field.forEach(item=>{
					item.value = ''
					item.ind = -1
				})
				this.form.field = data.field
				this.detail = data
				this.$util.hideAll()
				this.isLoad = true
			},
			pickerChange(e,index){
				let {
					value = 0
				} = e.detail
				this.form.field[index].ind = value
				console.log(e)
			},
			// 查看定位
			async toMap() {
				// #ifdef MP-WEIXIN
				let privacyCheck = this.$refs.user_privacy.check()
				if (privacyCheck) {
					this.$refs.user_privacy.open()
					return
				}
				// #endif
				let {
					address,
					lat,
					lng
				} = this.detail
				await this.$util.checkAuth({
					type: 'userLocation'
				})
				await uni.getLocation({
					type: 'gcj02',
				})
				await uni.openLocation({
					latitude: lat * 1,
					longitude: lng * 1,
					name: address,
					scale: 28
				})
			},
			countEnd(e){},
			imgUpload(e, index) {
				let {
					imagelist,
					imgtype
				} = e;
				this.form.field[index].value = imagelist;
			},
			toReplace(){
				this.isEditPhone = false
			},
			//表单验证
			validate(param, ruleType, is_send = false) {
				console.log(param, ruleType, is_send)
				let validate = new this.$util.Validate();
				this[`${ruleType}Rule`].map(item => {
					let {
						name,
					} = item
					if (ruleType == 'sub' && name == 'code' && is_send) return
					validate.add(param[name], item);
				})
				let message = validate.start();
				return message;
			},
			// 发送验证码
			async toSend() {
				let {
					authTime
				} = this
				if (authTime) return
				let {
					phone = ''
				} = this.form
				let msg = this.validate({
					phone
				}, 'sub', true);
				if (msg) {
					this.$util.showToast({
						title: msg
					});
					return;
				}
				if (this.lockTap) return
				this.lockTap = true
				this.$util.showLoading()
				try {
					await this.$api.user.sendShortMsg({
						phone
					})
					this.$util.hideAll()
					this.lockTap = false
					this.form.code = ''
					let time = 60
					this.timer = setInterval(() => {
						if (time === 0) {
							clearInterval(this.timer)
							return
						}
						time--
						this.authTime = time
					}, 1000)
				} catch (e) {
					setTimeout(() => {
						this.lockTap = false
						this.$util.hideAll()
					}, 2000)
				}
			},
			async submit() {
				let param = this.$util.deepCopy(this.form)
				if(!this.mineInfo.phone || !this.isEditPhone){
					let msg = this.validate(param, 'sub', !this.configInfo.short_code_status);
					if (msg) {
						this.$util.showToast({
							title: msg
						});
						return;
					}
					if(this.configInfo.short_code_status && param.code.length !== 6){
						this.$util.showToast({
							title: `请输入正确的验证码`
						})
						return
					}
				}else{
					param.phone = this.mineInfo.phone
				}
				let {
					field = []
				} = param
				console.log(param)
				let typeParam = {
					1: '请输入',
					2: '请选择',
					3: '请上传'
				}
				for(let i=0;i<field.length;i++){
					if(field[i].type == 3){
						field[i].value = field[i].value ? field[i].value[0].path : ''
					}else if(field[i].type == 2 && field[i].ind > -1){
						field[i].value = field[i].select[field[i].ind]
					}
					
					if(!field[i].value.replace(/(^\s*)|(\s*$)/g, "") && field[i].is_required == 1){
						this.$util.showToast({
							title: typeParam[field[i].type] + field[i].name
						});
						return;
					}
				}
				
				if(!this.$refs.show_payment.showPopup){
					this.$refs.show_payment.open()
					return
				}
				
				let {
					id: pay_model
				} = this.payList[this.payInd]
				
				let {
					join_price = 0
				} = this.detail
				let {
					some_balance: balance = 0
				} = this.mineInfo
				if(join_price*1 > balance*1 && pay_model == 2){
					this.$util.showToast({
						title: `账户余额不足`
					})
					return
				}
				
				param.pay_model = pay_model
				param.id = this.options.id
			
				if (this.lockTap) return
				this.lockTap = true
				this.$util.showLoading()
				try {
					let {
						pay_list,
						order_id = 0
					} = await this.$api.partner.joinPartner(param)
					this.$util.hideAll()
					if(pay_list){
						if (pay_model == 3) {
							pay_list = {
								orderInfo: pay_list,
								provider: 'alipay'
							}
						}
						// #ifdef H5
						if (pay_model == 3) {
							let {
								autograph
							} = this
							let alipay_params = `?autograph=${autograph}&id=${order_id}&aliptype=8`
							pay_list = Object.assign({}, pay_list, {
								order_id,
								page_url: `/pages/partner`,
								alipay_params
							})
							this.updateOrderItem({
								key: 'alipayOrderParams',
								val: pay_list
							})
							this.$util.goUrl({
								url: `/user/pages/alipay-result${alipay_params}`,
								openType: `redirectTo`
							})
							return
						}
						// #endif
						try {
							await this.$util.pay(pay_list)
							this.$util.showToast({
								title: `支付成功`
							})
							
							setTimeout(()=>{
								this.lockTap = false;
								this.$util.back()
								this.$util.goUrl({
									url: 1,
									openType: `navigateBack`
								})
							}, 1000)
						} catch (e) {
							this.$util.showToast({
								title: `支付失败`
							})
							this.lockTap = false;
							return;
						}
					}
					// 余额支付/零元支付
					this.$util.showToast({
						title: `支付成功`
					})
					setTimeout(() => {
						this.lockTap = false
						this.$util.back()
						this.$util.goUrl({
							url: 1,
							openType: `navigateBack`
						})
					}, 1000)				
				} catch (e) {
					setTimeout(() => {
						this.lockTap = false
						this.$util.hideAll()
					}, 2000)
				}
			}
		}
	}
</script>


<style lang="scss">
	.partner-info{
		.cover{
			width: 176rpx;
			height: 134rpx;
		}
		.detail-money-type{
			width: 68rpx;
			height: 36rpx;
			border-radius: 36rpx;
			border: 1px solid transparent;
		}
		.detail-time{
			height: 80rpx;
			background: #F8F5FF;
		}
		.left-icon{
			width: 65rpx;
		}
		.addr-icon{
			width: 69rpx;
			height: 69rpx;
			border-radius: 69rpx;
			right: 15rpx;
			top: 14rpx;
		}
	}
	.form-item{
		min-height: 96rpx;
		.form-item-title{
			min-width: 110rpx;
		}
		.form-item-input{
			height: 96rpx;
		}
		.form-item-btn{
			width: 150rpx;
			height: 60rpx;
			border-radius: 60rpx;
			border: 1px solid transparent;
		}
	}
	.form-item-textarea{
		height: 380rpx;
		width: 590rpx;
	}
	.h-90{
		height: 90rpx;
	}
	.footer-box{
		height: 120rpx;
		.footer-box-btn{
			width: 283rpx;
			height: 90rpx;
			border-radius: 90rpx;
		}
	}
</style>